package Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Tools.LoginTools;

public class UserRegisterServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);//调用自己的doPost方法
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1、设置请求对象中的编码格式
		req.setCharacterEncoding("UTF-8");
		//2、获取传入的账号及密码
		String username = req.getParameter("username");//获取账号
		String password = req.getParameter("password");//获取密码
		String phone = req.getParameter("phone");//获取电话号码
		String qq = req.getParameter("qq");//获取QQ号
		String email = req.getParameter("email");//获取邮箱
		String weixin = req.getParameter("weixin");//获取微信号
		//3、获取数据库连接
		System.out.println("username = " + username);
		System.out.println("password = " + password);
		System.out.println("phone" + phone);
		System.out.println("qq" + qq);
		System.out.println("email" + email);
		System.out.println("weixin" + weixin);
		Connection conn = LoginTools.getConnection();
		//4、准备SQL
		String sql = "insert into users(username,password,phone,qq,email,weixin) values(?, ?, ?, ?, ?, ?)";
		//5、获取声明对象
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			//6、补全SQL
			ps.setString(1,username);
			ps.setString(2,password);
			ps.setString(3,phone);
			ps.setString(4,qq);
			ps.setString(5,email);
			ps.setString(6,weixin);
			//、执行SQL并更新数据库
			int n =ps.executeUpdate();
			System.out.println("n = " + n);
			//8、解析结果
			if(n > 0) {
				//注册成功
				req.getRequestDispatcher("WebPages/login.html").forward(req, resp);
			}else {
				//如果没有数据就重定向到注册页
				resp.sendRedirect("WebPages/register.html");
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			//9、关闭资源
			LoginTools.closeResource(conn, ps, null);
		}
	}
}
